package com.authine.cloudpivot.ext.controller.purchase;

import cn.hutool.core.lang.Assert;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * pu采购-地区代码
 **/
@RestController
@RequestMapping("/public/regionCode")
@Slf4j
public class RegionCodeController extends BaseController {

    @Autowired
    CloudSqlService sqlService;

    @RequestMapping("finish")
    public void finish(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.REGION_CODE, bizId);

        //personnelInfoDetail  人员信息记录 人事信息子表
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("regionCodeDetail");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {
            try {
                //将子表中数据处理，随后更新至【地区代码 基础表】
                Map<String, Object> data = fileInfoBaseMap(map, now, approval);

                //判断是否已存在
                String id = existsBizObject(map);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.REGION_CODE_BASE, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("地区代码 基础表数据新增成功");

                //调用存储过程
                callProcess(id);
            } catch (Exception e) {
                log.info("地区代码 基础表数据维护失败，报错信息：{}", e.getMessage());
                String regionCode = (String) map.get("regionCode");
                String superiorRegionCode = (String) map.get("superiorRegionCode");
                log.info("基础表-人员信息基础操作失败 regionCode={},superiorRegionCode={}", regionCode, superiorRegionCode);
            }
        }
    }

    @RequestMapping("toVoid")
    public void toVoid(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.VOID_REGION_CODE, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("voidRegionCodeDetail");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //获取审批人
        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {
            try {
                //获取数据
                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(data);
                if (StringUtils.isEmpty(id)) {
                    //判断是否已存在，如果不存在，放弃这条数据，直接跳过此次循环
                    log.info("地区代码审批完成后，子表中的地区：{}，在基础数据表无数据，跳过作废", map.get("regionCode"));
                    continue;
                } else if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                    data.remove("regionCode");
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.REGION_CODE_BASE, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("地区代码作废操作成功");
                //调用存储过程
                callProcessToVoid(id);
            } catch (Exception e) {
                String regionCode = (String) map.get("regionCode");
                log.error("地区代码基础作废操作失败 regionCode={}", regionCode);
                log.error(e.getMessage(), e);
            }
        }
    }


    /**
     * 调用存储过程
     * ------地区代码 基础表
     * exec   SyncArea
     */
    private void callProcess(String bizId) {

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.REGION_CODE_BASE);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}", map);

        //调用存储过程
        String areaCode = MapUtils.getString(map, "regionCode", "");//地区代码
        String upCode = MapUtils.getString(map, "superiorRegionCode", "");//上级地区代码
        String areaName = MapUtils.getString(map, "regionName", "");//名称
        String type = MapUtils.getString(map, "type", "");//类别
        String typeNum;
        switch (type) {
            case "'大洲":
                typeNum = "1";
                break;
            case "国家":
                typeNum = "2";
                break;
            case "区域":
                typeNum = "3";
                break;
            case "省份":
                typeNum = "4";
                break;
            case "城市":
                typeNum = "5";
                break;
            case "区县":
                typeNum = "6";
                break;
            default:
                typeNum = "7";
                break;
        }

        String isDirect = MapUtils.getString(map, "municipality", "");//直辖市
        isDirect = "√".equals(isDirect) ? "1" : "0";
        String dailing = MapUtils.getString(map, "areaCode", "");//区号
        String status = MapUtils.getString(map, "status", "");//状态
        status = "启用".equals(status) ? "1" : "2";
        String mainDeptId = MapUtils.getString(map, "responsibleDeptCode", "");//主责部门FID
        String englishName = MapUtils.getString(map, "englishTranslation", "");//英译
        String auditor = MapUtils.getString(map, "auditer", "");//审批人


        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncArea '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                areaCode, upCode, areaName, typeNum, isDirect, dailing, status, mainDeptId, englishName, auditor);

        log.info("\n==========准备调用存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============存储过程执行完成");

    }

    /**
     * 调用作废存储过程
     * --------地区代码基础表 作废
     * exec    AreaDisable
     *
     * @param bizId
     * @CompanyFID nvarchar(100),            ----公司FID
     * @EmpCode nvarchar(100)            ----人员代码
     */
    private void callProcessToVoid(String bizId) {

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.REGION_CODE_BASE);
        StringBuilder sql = new StringBuilder("SELECT regionCode from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}", map);

        //调用存储过程

        String areaCode = MapUtils.getString(map, "regionCode", "");

        Assert.isFalse(StringUtils.isEmpty(areaCode), "{}不能为空", "regionCode");


        String execSql = String.format("exec [HG_LINK].[hg].[dbo].AreaDisable  '%s'",
                areaCode);

        log.info("\n==========准备调用作废存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============作废存储过程执行完成");

    }

    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject) {
        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = "Activity21";
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            final String finalActivityCode2 = "Activity20";
            Optional<WorkItemModel> second = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode2)).findFirst();
            if (second.isPresent()) {
                WorkItemModel workItemModel = second.get();
                participant = workItemModel.getParticipant();
            }
        }


        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append("　").append(user.getName()).toString();
    }


    /**
     * 判断是否已存在
     *
     * @return
     */
    private String existsBizObject(Map data) {

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.REGION_CODE_BASE);
        String regionCode;
        if (data.get("regionCode") instanceof Map) {
            Map<String,Object> regionMap = (Map<String, Object>) data.get("regionCode");
            regionCode = (String) regionMap.get("regionCode");
        } else {
            regionCode = (String) data.get("regionCode");
        }

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where regionCode='").append(regionCode).append("';");
        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     * 转换成  基础表-总公司档案 的数据
     *
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String, Object> fileInfoBaseMap(Map<String, Object> map, String auditDate, String auditer) {
        Map<String, Object> data = new HashMap<>();
        //地区代码
        data.put("regionCode", map.get("regionCode"));
        //上级地区代码
        data.put("superiorRegionCode", map.get("superiorRegionCode"));
        //上级地区责任部门代码
        data.put("superiorDeptCode", map.get("superiorDeptCode"));
        //名称
        data.put("regionName", map.get("regionName"));
        //类型
        data.put("type", map.get("type"));
        //直辖市
        data.put("municipality", map.get("municipality"));
        //区号
        data.put("areaCode", map.get("areaCode"));
        //状态
        data.put("status", map.get("status"));
        //责任部门代码
        Map<String,Object> responsibleDeptMap = (Map<String, Object>) map.get("responsibleDept");
        data.put("responsibleDept", responsibleDeptMap.get("id"));
        //责任部门隐藏代码
        data.put("responsibleDeptCode", map.get("responsibleDeptCode"));
        //责任部门
        data.put("responsibleDeptName", map.get("responsibleDeptName"));
        //英译
        data.put("englishTranslation", map.get("englishTranslation"));
        //审批时间
        data.put("auditDate", auditDate);
        //审批人
        data.put("auditer", auditer);
        return data;
    }
}
